﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GAIA_Logica;

namespace GAIA_IU
{
    public partial class ModificarEstudio : System.Web.UI.Page
    {
        Estudio estudio = new Estudio();
        List<Elemento> listaElementos = new List<Elemento>();

        protected void Page_Load(object sender, EventArgs e)
        {
            getEstudioDetalle();
        }
        
        protected void btn_salvar_Click(object sender, EventArgs e)
        {
            //Eliminar inventario asociado al estudio
            eliminarInventario();


            try
            {

                //estudio = new Estudio(id_cliente, id_parcela);
                //estudio.ingrearEstudio();
                if (insertarElementos(estudio.CodEstudio))
                {
                    Avisar("Un nuevo estudio de terreno ha sido ingresado al sistema", true);
                }
                else
                {
                    Avisar("Error al ingresar el estudio. Por favor intente nuevamente", false);
                }

                getEstudioDetalle();

                //ClearForm();
            }
            catch (Exception ex)
            {
                Avisar("Error al ingresar el estudio. Por favor intente nuevamente :(" + ex.Message + ")", false);
            }

        }

        protected void eliminarInventario(){
            foreach(Elemento tmp_elemento in listaElementos){
                tmp_elemento.borrarElemento();
            }
        }
        
        protected bool insertarElementos(int cod_estudio)
        {
            bool result = false;
            //List<GAIA_Logica.Segmento> listaSegmentos;
            GAIA_Logica.Elemento tempElemento;
            int cant_especies = int.Parse(Request["cant_especies"]);
            try
            {
                for (int x = 0; x < cant_especies; x++)
                {
                    if (Request["especies[" + x + "].dap"] != null)
                    {
                        int pid_especie = int.Parse(Request["especies[" + x + "].id"]);

                        string _db_DAP = (Request["especies[" + x + "].dap"]);
                        string db_DAP = _db_DAP.Replace(".", ",");
                        double pDap = double.Parse(db_DAP);

                        string _db_HC = (Request["especies[" + x + "].hc"]);
                        string db_HC = _db_HC.Replace('.', ',');
                        double pHc = double.Parse(db_HC);

                        string _db_volumen = (Request["especies[" + x + "].calculo"]);
                        string db_volumen = _db_volumen.Replace('.', ',');
                        double pVolumen = double.Parse(db_volumen);

                        string _db_arebasal = (Request["especies[" + x + "].areabasal"]);
                        string db_arebasal = _db_arebasal.Replace('.', ',');
                        double pAreaBasal = double.Parse(db_arebasal);


                        string _lambertN = (Request["especies[" + x + "].lambertN"]);
                        string lambertN = _lambertN.Replace('.', ',');
                        double pLambertN = double.Parse(lambertN);

                        string _lambertE = (Request["especies[" + x + "].lambertE"]);
                        string lambertE = _lambertE.Replace('.', ',');
                        double pLambertE = double.Parse(lambertE);

                        pLambertE = getMinDec(pLambertE);
                        pLambertN = getMinDec(pLambertN);

                        double crtm05N = getCrmt05N(pLambertN, pLambertE);
                        double crtm05E = getCrmt05E(pLambertN, pLambertE);

                        tempElemento = new Elemento(pDap, pHc, pVolumen, pAreaBasal, pid_especie, cod_estudio, pLambertN, pLambertE, crtm05N, crtm05E);
                        result = tempElemento.ingresaElemento();
                    }
                }
            }
            catch (Exception ex)
            {
                Avisar("Error al ingresar las parcelas. Por favor intente nuevamente :(" + ex.Message + ")", false);
                result = false;
            }
            return result;
        }

        private void getEstudioDetalle() {

            //Genera el objeto estudio
            string codEstudio = Request["codEstudio"];
            estudio.getEstudioxId(int.Parse(codEstudio));

            //Obtener la lista de especies
            List<Especies> listaEspecies = new List<Especies>();
            Especies tmp_especie = new Especies();
            listaEspecies = tmp_especie.getListaEspecies();
            //Session["id_segemento"] = (Int32)GridView_Parcelas.SelectedDataKey.Values["Id"];
            rptPlants.DataSource = listaEspecies;
            rptPlants.DataBind();

            //Obtener la lista de especies en inventario
            Elemento tmp_elemento = new Elemento();
            listaElementos = tmp_elemento.getElementosCenso(estudio.CodEstudio);
            rptElementos.DataSource = listaElementos;
            rptElementos.DataBind();

            //Mostrar datos básicos del estudio
            this.lb_Cliente.Text = estudio.Cliente.Nombre + " " + estudio.Cliente.Ap1 + " " + estudio.Cliente.Ap2;
            this.lb_Parcela.Text = "" + estudio.Terreno.Nombre;
            this.lb_Finca.Text = "" + estudio.Terreno.Terreno_padre.Nombre;

        }

        protected void Avisar(string aviso, bool resultado)
        {
            aviso_label.Text = aviso;
            if (resultado)
            {
                aviso_label.CssClass = "_true";
            }
            else
            {
                aviso_label.CssClass = "_false";
            }

        }

        //Obtiene crmt05N apartir de lambert norte ye 
        private double getCrmt05N(double nl, double el)
        {
            double result = 0.0;

            double fe = 500000.0;
            double e = (el - fe) * 0.00001;

            if (nl > 0 && el > 0)
            {
                double fn = 271820.52;
                double n = (nl - fn) * 0.00001;
                double a00 = 1156874.11;
                double a10 = 99964.18;
                double a01 = -105.22;
                double a20 = -0.01;
                double a11 = -8.97;
                double a30 = -4.15;
                double a21 = 0.03;
                double a12 = 12.37;
                double a03 = 0;
                double b00 = 463736.66;
                double b10 = 105.19;
                double b01 = 99964.19;
                double b20 = 4.49;
                double b02 = -4.49;
                double b21 = -12.39;
                double b12 = 0.03;
                double b03 = 4.12;

                double n90 = a00 + a10 * n + a01 * e + a20 * n * n + a11 * n * e + a30 * n * n * n + a21 * n * n * e + a12 * n * e * e + a03 * e * e * e;
                double e90 = b00 + b10 * n + b01 * e + b20 * n * n + b02 * e * e + b21 * n * n * e + b12 * n * e * e + b03 * e * e * e;

                if (!((n90 < 1056672 || n90 > 1237077) || (e90 < 283690 || e90 > 663760)))
                {
                    double a0 = -7.75237044;
                    double b0 = -3.525688428;
                    double a1 = 1.00000086635;
                    double b1 = -0.00000000018;
                    double n98 = a0 + a1 * n90 - b1 * e90;
                    double e98 = b0 + a1 * e90 + b1 * n90;
                    a0 = -0.179913184;
                    b0 = -149.644487588;
                    a1 = 1.00030018487;
                    b1 = -0.00000034731;
                    result = a0 + a1 * n98 - b1 * e98;

                }

            }

            result = getMinDec(result);
            return result;
        }

        private double getCrmt05E(double nl, double el)
        {
            double result = 0.0;

            double fe = 500000.0;
            double e = (el - fe) * 0.00001;


            if (nl > 0 && el > 0)
            {
                double fn = 271820.52;
                double n = (nl - fn) * 0.00001;
                double a00 = 1156874.11;
                double a10 = 99964.18;
                double a01 = -105.22;
                double a20 = -0.01;
                double a11 = -8.97;
                double a30 = -4.15;
                double a21 = 0.03;
                double a12 = 12.37;
                double a03 = 0;
                double b00 = 463736.66;
                double b10 = 105.19;
                double b01 = 99964.19;
                double b20 = 4.49;
                double b02 = -4.49;
                double b21 = -12.39;
                double b12 = 0.03;
                double b03 = 4.12;

                double n90 = a00 + a10 * n + a01 * e + a20 * n * n + a11 * n * e + a30 * n * n * n + a21 * n * n * e + a12 * n * e * e + a03 * e * e * e;
                double e90 = b00 + b10 * n + b01 * e + b20 * n * n + b02 * e * e + b21 * n * n * e + b12 * n * e * e + b03 * e * e * e;

                if (!((n90 < 1056672 || n90 > 1237077) || (e90 < 283690 || e90 > 663760)))
                {
                    double a0 = -7.75237044;
                    double b0 = -3.525688428;
                    double a1 = 1.00000086635;
                    double b1 = -0.00000000018;
                    double n98 = a0 + a1 * n90 - b1 * e90;
                    double e98 = b0 + a1 * e90 + b1 * n90;
                    a0 = -0.179913184;
                    b0 = -149.644487588;
                    a1 = 1.00030018487;
                    b1 = -0.00000034731;
                    result = b0 + a1 * e98 + b1 * n98;

                }

            }

            result = getMinDec(result);
            return result;
        }

        private double getMinDec(double value)
        {
            double result = Math.Round(value, 5);
            return result;
        }
    }
}